package com.appsino.bingluo.secret.http;

import android.util.Log;

import java.net.SocketTimeoutException;

import androidx.annotation.CallSuper;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Created by Answer on 2018/3/1.
 */

public abstract class BaseObserver<T> implements Observer<BaseCallModel<T>> {
    private final int RESPONSE_CODE_OK = 0;       //自定义的业务逻辑，成功返回积极数据
    private int errorCode;
    private String errorMsg = "服务器繁忙，请稍后重试";
    private final int RESPONSE_CODE_FAILED = -1;  //返回数据失败,严重的错误
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseCallModel<T> response) {
            //网络数据返回
            onSuccess(response);
    }

    @Override
    public void onError(Throwable t) {
        Log.i("TAG", "------->info:" + t);
        if(t instanceof HttpException){
            HttpException httpException = (HttpException) t;
            errorCode = httpException.code();
            errorMsg = httpException.message();
        }else if(t instanceof SocketTimeoutException){
            errorCode = RESPONSE_CODE_FAILED;
            errorMsg = "网络繁忙，请稍后再试";
        }
        onFailure(errorCode,errorMsg);
    }

    @Override
    public void onComplete() {

    }
    /**
     * 根据具体的Api 业务逻辑去重写 onSuccess 方法！Error 是选择重写，but 必须Super ！
     * @param response
     */
    public abstract void onSuccess(BaseCallModel<T> response);
    /**
     * Default error dispose!
     * 一般的就是 AlertDialog 或 SnackBar
     *
     * @param code
     * @param message
     */
    @CallSuper//if overwrite,you should let it run.
    public void onFailure(int code, String message) {
    }

}
